package com.zhentao.controller;

import com.alibaba.fastjson2.JSONObject;
import com.zhentao.pojo.WxLoginProperties;
import com.zhentao.utils.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
@Api(tags = "WxLoginController-app微信登录")
public class WxLoginController {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private WxLoginProperties wxLoginProperties;
    @ApiOperation("登录")
    @GetMapping("/wxlogin")
    public ResponseResult login(@RequestParam("code") String code) {
        if (StringUtils.isEmpty(code)) {
            return ResponseResult.errorResult(22008, "登录失败，请重新尝试");
        }

        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                wxLoginProperties.getAppid(), wxLoginProperties.getAppsecret(), code);
        try {
            String forObject = restTemplate.getForObject(accessTokenUrl, String.class);
            JSONObject jsonObject = JSONObject.parseObject(forObject);
            String sessionKey = jsonObject.getString("session_key");
            String openid = jsonObject.getString("openid");
            log.info("获取到的session_key: {}, openid: {}", sessionKey, openid);
            return ResponseResult.okResult(200, "操作成功").ok(openid);
        } catch (Exception e) {
            log.error("调用微信登录API失败", e);
            return ResponseResult.errorResult(500, "系统异常，请稍后重试");
        }
    }
}
